import axios from 'axios'
import {ElMessage} from 'element-plus'
//import { refresh } from '../api/userLogin'
import {getToken, removeToken} from '@/utils/auth'
import router from "../router";

// export const baseURL='http://123.56.131.61:8000'
export const baseURL = 'http://120.55.50.49:8000'


const service = axios.create({
    // baseURL: '/api',
    baseURL: baseURL,
    timeout: 50000
})

// 请求拦截: 每一次发请求都会做的事情
service.interceptors.request.use(
    config => {
        const token = getToken() as string
        if (token) {
            config.headers!['Authorization'] = `Bearer ${token}`;
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)


//响应拦截
service.interceptors.response.use((response) => {
    ElMessage.closeAll();

    if (response.data.code == 200) {
        if (response.data.message !== '查询成功') {
            ElMessage({
                message: response.data.message,
                type: "success",
                duration: 2 * 1000
            })
        }
        return response.data

    } else {
        ElMessage({
            message: response.data.message,
            type: 'error',
            duration: 2 * 1000
        })
    }


}, (err) => {
    console.log(err)
    const res = err

    ElMessage.closeAll();
    // removeToken()
    if (res.response.status === 401) {
        removeToken()
        ElMessage({
            message: "登陆信息已过期",
            type: 'error',
            duration: 2 * 1000
        })
    } else if (res.response.status === 403) {
        ElMessage({
            message: '该操作需要登陆',
            type: 'error',
            duration: 2 * 1000
        })
    } else {
        ElMessage({
            message: '网络异常',
            type: 'error',
            duration: 2 * 1000
        })
    }

    return Promise.reject(err)
})

export default service
